<?php namespace Phphub\Creators;

use Phphub\Forms\EvaluationCreationForm;
use Phphub\Core\CreatorListener;
use Phphub\Core\Robot;
use Lab;
use Evaluation;
use Auth;
use Carbon;
use Markdown;

class EvaluationCreator
{
    protected $form;

    public function __construct(EvaluationCreationForm $form)
    {
        $this->form = $form;
    }

    public function create(CreatorListener $observer, $data)
    {
        $data['user_id'] = Auth::id();
        $data['created_at'] = Carbon::now()->toDateTimeString();
        $data['updated_at'] = Carbon::now()->toDateTimeString();

        $markdown = new Markdown;
        $data['body_original'] = $data['body'];
        $data['body'] = $markdown->convertMarkdownToHtml($data['body']);

        // Validation
        $this->form->validate($data);

        $evaluation = Evaluation::create($data);
        if (! $evaluation) {
            return $observer->creatorFailed($evaluation->getErrors());
        }
        $evaluation->lab->increment('evaluation_count', 1);

        Robot::notify($data['body_original'], 'Evaluation', $evaluation, Auth::user());

        return $observer->creatorSucceed($evaluation);
    }
}
